package com.irisking.server.client;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.irisking.server.coder.ConstantValue;
import com.irisking.server.entity.TransforData;

/**
 * 会话管理者
 * @author -weiz-
 *
 */
public class ClientManager {

	/**
	 * 在线设备列表
	 */
	private static final ConcurrentHashMap<String, DeviceClient> onlineClients = new ConcurrentHashMap<>();
	
	/**
	 * 加入
	 * @param key
	 * @param deviceClient
	 * @return
	 */
	public static boolean put(String key, DeviceClient deviceClient){
		if(!onlineClients.containsKey(key)){
			boolean success = onlineClients.putIfAbsent(key, deviceClient)== null ? true : false;
			return success;
		}
		return false;
	}
	
	/**
	 * 移除在线列表
	 * @param key
	 */
	public static DeviceClient remove(String key){
		return onlineClients.remove(key);
	}

	/**
	 * 发送消息[自定义协议]
	 * @param key
	 * @param data
	 */
	public static void sendCommandData(String key, String data) {
		DeviceClient deviceClient = onlineClients.get(key);
		if (deviceClient != null && deviceClient.isConnected()) {
			TransforData respData = new TransforData(ConstantValue.REQ_TRANS_JSON_TO_CLIENT, ConstantValue.COMM_SUB_CODE, data.getBytes());
			deviceClient.write(respData);
		}
	}

	/**
	 * 发送消息[自定义协议]
	 * @param key
	 * @param data
	 */
	public static void sendAckData(String key, String data) {
		DeviceClient deviceClient = onlineClients.get(key);
		if (deviceClient != null && deviceClient.isConnected()) {
			TransforData respData = new TransforData(ConstantValue.ACK_TRANS_JSON_TO_SRV, ConstantValue.COMM_SUB_CODE, data.getBytes());
			deviceClient.write(respData);
		}
	}

	/**
	 * 获取连接
	 * @param key
	 * @return
	 */
	public static DeviceClient get(String key) {
		return onlineClients.get(key);
	}

	/**
	 * 获取全部连接
	 * @return
	 */
	public static List<String> getAll(){
		return Collections.list(onlineClients.keys());
	}

	/**
	 * 处理心跳请求
	 * @param key
	 */
	public static void heartBeat(String key) {
		DeviceClient deviceClient = onlineClients.get(key);
		if (deviceClient != null && deviceClient.isConnected()) {
			deviceClient.setBeatCount(0);
		}
	}
}
